import dayjs from 'dayjs'

/**
 * 转化 2024-09-09 08:21:00 为 **前
 */
export const getTimeStr = (timestamp) => {
  const now = new Date()
  const date = new Date(timestamp)

  const diff = (now - date) / 1000 // 毫秒转换为秒

  if (diff < 60) {
    return '刚刚'
  } else if (diff < 3600) {
    return Math.floor(diff / 60) + '分钟前'
  } else if (diff < 86400) {
    return Math.floor(diff / 3600) + '小时前'
  } else if (diff < 604800) {
    return Math.floor(diff / 86400) + '天前'
  } else {
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()
    return `${year}-${month < 10 ? '0' + month : month}-${day < 10 ? '0' + day : day}`
  }
}

/**
 * 时间戳转成 2024/09/09 08:21
 */
export const getDateTimeStr = (timestamp) => {
  return dayjs(timestamp).format('YYYY/MM/DD HH:mm')
}

/**
 * 传入日期字符串，返回距离当前时间还有多少天多少小时
 * @param {string} dateStr - 目标日期字符串，格式：YYYY-MM-DD HH:mm:ss
 * @return {string} 返回格式化后的时间差，例如：1天2小时
 */
export function getTimeRemaining(dateStr) {
  // 将日期字符串转换为时间戳
  const timestamp = new Date(dateStr.replace(/-/g, '/')).getTime()

  // 计算时间差（毫秒）
  const now = Date.now()
  const diff = timestamp - now

  // 如果时间已过期，返回已结束
  if (diff <= 0) {
    return '已结束'
  }

  // 计算天数和小时
  const days = Math.floor(diff / (24 * 60 * 60 * 1000))
  const hours = Math.floor((diff % (24 * 60 * 60 * 1000)) / (60 * 60 * 1000))

  // 组装返回字符串
  let result = ''
  if (days > 0) {
    result = `${days}天`
  }
  if (days === 0) {
    result = `${hours}小时`
  }

  return result
}

// 将文本中的网址样式修改为蓝色，并添加链接
export const formatText = (text) => {
  // 如果文本为空，直接返回
  if (!text) return text

  // 创建一个临时DOM元素来解析HTML
  const tempDiv = document.createElement('div')
  tempDiv.innerHTML = text

  // 获取所有文本节点
  const textNodes = []
  const walk = document.createTreeWalker(tempDiv, NodeFilter.SHOW_TEXT, null, false)

  let node
  while ((node = walk.nextNode())) {
    textNodes.push(node)
  }
  // 处理每个文本节点中的URL
  textNodes.forEach((textNode) => {
    const text = textNode.nodeValue
    const urlRegex = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gi
    const urls = text.match(urlRegex)

    if (urls) {
      let lastIndex = 0
      let result = ''

      urls.forEach((url) => {
        // 找到URL在文本中的位置
        const index = text.indexOf(url, lastIndex)
        if (index !== -1) {
          // 添加URL前的文本
          result += text.substring(lastIndex, index)
          // 添加带链接的URL
          result += `<a href="${url}" style="color: #aaaaff;">${url}</a>`
          lastIndex = index + url.length
        }
      })

      // 添加剩余的文本
      result += text.substring(lastIndex)

      // 创建新的HTML元素替换文本节点
      const span = document.createElement('span')
      span.innerHTML = result
      textNode.parentNode.replaceChild(span, textNode)
    }
  })

  return tempDiv.innerHTML
}



export const  formatTime = (data)=> {
  if (!data) return ''

  let timestamp
  if (typeof data === 'string') {
    timestamp = new Date(data.replace(/-/g, '/')).getTime()
  } else {
    timestamp = data.toString().length === 10 ? data * 1000 : data
    timestamp = new Date(timestamp).getTime()
  }

  const timePublish = new Date(timestamp)
  const timeNow = new Date()
  const minute = 1000 * 60
  const hour = minute * 60
  const day = hour * 24
  const month = day * 30
  const year = month * 12
  const diffValue = timeNow - timePublish

  if (diffValue < 0) return '刚刚'

  const diffYear = diffValue / year
  const diffMonth = diffValue / month
  const diffWeek = diffValue / (7 * day)
  const diffDay = diffValue / day
  const diffHour = diffValue / hour
  const diffMinute = diffValue / minute

  if (diffValue < minute) {
    return '刚刚'
  } else if (diffYear > 1) {
    return Math.floor(diffYear) + '年前'
  } else if (diffMonth > 1) {
    return Math.floor(diffMonth) + '月前'
  } else if (diffWeek > 1) {
    return Math.floor(diffWeek) + '周前'
  } else if (diffDay > 1) {
    return Math.floor(diffDay) + '天前'
  } else if (diffHour > 1) {
    return Math.floor(diffHour) + '小时前'
  } else if (diffMinute > 1) {
    return Math.floor(diffMinute) + '分钟前'
  } else {
    return '刚刚'
  }
}